package org.dhbw.jee.web.beans;

import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;

import org.dhbw.jee.business.db.User;
import org.dhbw.jee.persistence.dataAccess.DataAccessObject;
import org.dhbw.jee.web.security.Hash;

@Named("loginController")
@SessionScoped
public class LoginController extends AbstractController {
	private static final long serialVersionUID = 1L;

	@Inject
	Credentials credentials;

	@Inject
	DataAccessObject dao;

	private User user;

	public String login() {
		try {

			String hashedPW = Hash.toMD5(credentials.getPassword());
			String nickName = credentials.getNickName();

			System.out.println(nickName + " " + hashedPW);

			user = dao.getSingleByQuery(User.class, User.BY_NICK_AND_PASS, nickName, hashedPW);

			System.out.println(user);
			System.out.println(user.getNickName() + " - " + user.getPassword() + " - " + user.getAlbums().size() + " Albums - logged in");

			return "base?faces-redirect=true";
		} catch (Exception e) {
			e.printStackTrace();
			user = null;
			return "login?faces-redirect=true";
		}
	}

	public String logout() {
		System.out.println(user);
		System.out.println(user.getNickName() + " logged out");
		user = null;
		return "login?faces-redirect=true";
	}

	public boolean isLoggedIn() {
		return user != null;
	}

	public String register() {
		System.out.println("User: " + user);

		return login();
	}

	public User getUser() {
		return user;
	}

}
